package org.lex.keytool.core.service;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.lex.keytool.core.task.CreatePublicAndPrivateKeyTask;
import org.lex.keytool.core.task.ExportCertificateTask;
import org.lex.keytool.core.task.ImportCertificateTask;
import org.lex.keytool.core.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TaskService {
	private static final TaskService INSTANCE = new TaskService();

	public static TaskService getInstance() {
		return INSTANCE;
	}

	public Collection<String> getTaskNames() {
		return map.keySet();
	}

	public Class<? extends Task> getTaskClass(String taskName) {
		return map.get(taskName);
	}

	public String getTaskName(Class<? extends Task> taskClass) {
		for (Map.Entry<String, Class<? extends Task>> e : map.entrySet()) {
			if (e.getValue().equals(taskClass)) {
				return e.getKey().replace('.', ' ');
			}
		}
		return "";
	}

	public Task createTask(String taskName) {
		Class<? extends Task> clz = map.get(taskName);
		Task ins = null;
		if (null != clz) {
			try {
				ins = clz.newInstance();
			} catch (InstantiationException e) {
				log.error("", e);
			} catch (IllegalAccessException e) {
				log.error("", e);
			}
		}
		return ins;
	}

	// <taskName, taskClass>
	private Map<String, Class<? extends Task>> map = new HashMap<String, Class<? extends Task>>();
	private Logger log = LoggerFactory.getLogger(TaskService.class);

	private TaskService() {
		map.put("Create.Public and Private Keys", CreatePublicAndPrivateKeyTask.class);
		map.put("Export.Certificate", ExportCertificateTask.class);
		map.put("Import.Certificate", ImportCertificateTask.class);
	}
}
